<script setup lang="ts">
import { ref, watch } from 'vue';
import { ElDialog, ElTree, ElButton } from 'element-plus';
import { $t } from '@/locales';
import { queryMenuPermission, queryPermissionIdsWithRoleId, add } from '@/service/api/system-manage';

// Props
const props = defineProps({
  visible: Boolean,
  roleId: [Number, String]
});

// Emits
const emit = defineEmits(['update:visible', 'close', 'success']);

// State
const loading = ref(false);
const submitLoading = ref(false);
const permissionTree = ref([]);
const checkedPermissionIds = ref([]);
const fetchError = ref(false);

// Tree config
const defaultProps = {
  children: 'children',
  label: 'title'
};

// Methods
function closeDialog() {
  emit('update:visible', false);
  emit('close');
}

async function loadPermissionTree() {
  loading.value = true;
  fetchError.value = false;
  
  try {
    const res = await queryMenuPermission();
    permissionTree.value = Array.isArray(res?.data) ? res.data : [];
    console.log('Permission tree loaded:', permissionTree.value.length, 'items');
  } catch (error) {
    console.error('Failed to load permission tree:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

async function loadCheckedPermissions() {
  if (!props.roleId) return;
  
  const roleId = Number(props.roleId);
  loading.value = true;
  
  try {
    const res = await queryPermissionIdsWithRoleId(roleId);
    checkedPermissionIds.value = Array.isArray(res?.data) 
      ? res.data.map(id => Number(id)).filter(Boolean)
      : [];
    console.log('Checked permissions loaded:', checkedPermissionIds.value.length, 'items');
  } catch (error) {
    console.error('Failed to load role permissions:', error);
    fetchError.value = true;
  } finally {
    loading.value = false;
  }
}

function handleCheck(_data, checked) {
  if (checked?.checkedKeys) {
    checkedPermissionIds.value = Array.isArray(checked.checkedKeys)
      ? checked.checkedKeys.map(id => Number(id)).filter(Boolean)
      : [];
  }
}

async function handleSubmit() {
  if (!props.roleId) {
    window.$message?.warning('请选择角色');
    return;
  }
  
  submitLoading.value = true;
  
  try {
    const params = {
      roleId: Number(props.roleId),
      permissionIds: checkedPermissionIds.value
    };
    
    const result = await add(params);
    
    if (result) {
      window.$message?.success('权限更新成功');
      emit('success');
      closeDialog();
    } else {
      window.$message?.error('提交失败');
    }
  } catch (error) {
    console.error('提交权限配置失败:', error);
    window.$message?.error('提交失败');
  } finally {
    submitLoading.value = false;
  }
}

function refreshData() {
  checkedPermissionIds.value = [];
  permissionTree.value = [];
  loadPermissionTree();
  loadCheckedPermissions();
}

// Watch for dialog visibility
watch(() => props.visible, (val) => {
  console.log('Dialog visibility changed:', val);
  if (val) {
    refreshData();
  }
});

// Watch for role ID changes
watch(() => props.roleId, (val, oldVal) => {
  console.log('Role ID changed from', oldVal, 'to', val);
  if (props.visible && val !== oldVal) {
    refreshData();
  }
});
</script>

<template>
  <div>
    <el-dialog
      v-model="props.visible"
      :title="$t('common.edit') + ' 权限配置'"
      width="600px"
      destroy-on-close
      @closed="closeDialog"
    >
      <div v-loading="loading" class="h-400px overflow-auto">
        <div v-if="fetchError" class="flex-center h-full">
          <div class="text-center">
            <div class="text-red-500 text-xl mb-4">操作失败</div>
            <div class="mb-4">获取权限数据失败，请刷新重试</div>
            <el-button type="primary" @click="refreshData">重新加载</el-button>
          </div>
        </div>
        <el-tree
          v-else
          node-key="id"
          :data="permissionTree"
          :props="defaultProps"
          :default-checked-keys="checkedPermissionIds"
          :default-expanded-keys="checkedPermissionIds"
          show-checkbox
          @check="handleCheck"
        />
      </div>
      <template #footer>
        <div class="flex justify-end">
          <el-button @click="closeDialog">{{ $t('common.cancel') }}</el-button>
          <el-button 
            type="primary" 
            :loading="submitLoading" 
            @click="handleSubmit"
          >
            {{ $t('common.confirm') }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.h-400px {
  height: 400px;
}
.h-full {
  height: 100%;
}
.flex-center {
  display: flex;
  justify-content: center;
  align-items: center;
}
.flex {
  display: flex;
}
.justify-end {
  justify-content: flex-end;
}
.text-center {
  text-align: center;
}
.text-red-500 {
  color: #f56c6c;
}
.text-xl {
  font-size: 1.25rem;
}
.mb-4 {
  margin-bottom: 1rem;
}
</style> 